<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use App\Models\AdImage;
use App\Models\Goods;
use App\Models\Store;
use App\Models\StoreCategory;
use App\Models\StoreGoods;
use App\Models\Address;
use App\Models\StoreCashierSwitchCodeGroupRelation;
use App\Models\StoreCashierSwitchCodeGroupProperties;
use App\Models\StoreProductGroup;
use App\Models\StoreProductGroupProduct;
use App\Services\ImageUrlService;
use App\Models\StoreGroup;
use App\Models\StoreGroupStore;
use App\Models\PickupPointVendor;
use App\Models\Vendor;
use App\Models\HhmGoods;
use App\Models\HhmGoodsOption;
use Illuminate\Support\Facades\DB;

class SameCityController extends BaseApiController
{
    /**
     * 根据dispatch_type数组生成配送方式文本
     *
     * @param array|string|int $dispatchType 配送类型数组/字符串/数字
     * @return array 配送方式文本数组
     */
    private function getDispatchText($dispatchType)
    {
        if (is_numeric($dispatchType)) {
            $dispatchType = [(int) $dispatchType];
        } elseif (is_string($dispatchType)) {
            $decoded = json_decode($dispatchType, true);
            if (is_array($decoded)) {
                $dispatchType = $decoded;
            } elseif (is_numeric($dispatchType)) {
                $dispatchType = [(int) $dispatchType];
            } else {
                $dispatchType = [];
            }
        } elseif (! is_array($dispatchType)) {
            $dispatchType = [];
        }
        if (empty($dispatchType)) {
            return [];
        }
        $typeMap = [
            1  => '快递',
            2  => '上门自提',
            3  => '门店配送',
            12 => '门店自提点提货',
        ];
        $result = [];
        foreach ($dispatchType as $type) {
            if (isset($typeMap[$type])) {
                $result[] = $typeMap[$type];
            }
        }
        return $result;
    }

    /**
     * 查询门店支持的置换类型
     *
     * @param int $storeId 门店ID
     * @return array 置换类型数组
     */
    private function getStoreSwapTypes($storeId)
    {
        $swapTypes = [];
        try {
            $relations = StoreCashierSwitchCodeGroupRelation::where('store_id', $storeId)
                ->where('state', 1)
                ->get();
            if (! $relations->isEmpty()) {
                $groupPropertieIds = $relations->pluck('group_propertie_id')->filter()->unique()->toArray();
                if (! empty($groupPropertieIds)) {
                    $properties = StoreCashierSwitchCodeGroupProperties::whereIn('id', $groupPropertieIds)
                        ->where('state', 1)
                        ->get(['in_type', 'in_type_name']);
                    foreach ($properties as $prop) {
                        $swapTypes[] = [
                            'in_type'      => $prop->in_type,
                            'in_type_name' => $prop->in_type_name,
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            $swapTypes = [];
        }
        return $swapTypes;
    }

    /**
     * 批量查询门店支持的置换类型
     *
     * @param array $storeIds 门店ID数组
     * @return array 门店ID => 置换类型数组的映射
     */
    private function getBatchStoreSwapTypes($storeIds)
    {
        if (empty($storeIds)) {
            return [];
        }

        $swapTypesMap = [];
        try {
            // 批量获取关系数据
            $relations = StoreCashierSwitchCodeGroupRelation::whereIn('store_id', $storeIds)
                ->where('state', 1)
                ->get(['store_id', 'group_propertie_id']);

            if ($relations->isEmpty()) {
                return array_fill_keys($storeIds, []);
            }

            // 按门店ID分组
            $relationsByStore = $relations->groupBy('store_id');
            $groupPropertieIds = $relations->pluck('group_propertie_id')->filter()->unique()->toArray();

            if (!empty($groupPropertieIds)) {
                // 批量获取属性数据
                $properties = StoreCashierSwitchCodeGroupProperties::whereIn('id', $groupPropertieIds)
                    ->where('state', 1)
                    ->get(['id', 'in_type', 'in_type_name'])
                    ->keyBy('id');

                // 为每个门店组装置换类型
                foreach ($storeIds as $storeId) {
                    $swapTypes = [];
                    if (isset($relationsByStore[$storeId])) {
                        foreach ($relationsByStore[$storeId] as $relation) {
                            if (isset($properties[$relation->group_propertie_id])) {
                                $prop = $properties[$relation->group_propertie_id];
                                $swapTypes[] = [
                                    'in_type'      => $prop->in_type,
                                    'in_type_name' => $prop->in_type_name,
                                ];
                            }
                        }
                    }
                    $swapTypesMap[$storeId] = $swapTypes;
                }
            } else {
                $swapTypesMap = array_fill_keys($storeIds, []);
            }
        } catch (\Exception $e) {
            $swapTypesMap = array_fill_keys($storeIds, []);
        }

        return $swapTypesMap;
    }

    /**
     * 批量查询门店的供货商信息（用于判断上门自提）
     *
     * @param array $storeIds 门店ID数组
     * @return array 门店ID => 供货商数据的映射
     */
    private function getBatchStorePickupVendors($storeIds)
    {
        if (empty($storeIds)) {
            return [];
        }

        $pickupVendorsMap = [];
        try {
            // 批量查询自提点供货商关系
            $pickupPoints = PickupPointVendor::whereIn('store_id', $storeIds)
                ->get(['store_id', 'vendor_id']);

            if ($pickupPoints->isEmpty()) {
                return array_fill_keys($storeIds, [
                    'supports_pickup' => false,
                    'vendor_ids' => [],
                    'vendors' => []
                ]);
            }

            // 按门店ID分组
            $pointsByStore = $pickupPoints->groupBy('store_id');
            
            // 获取所有供货商ID
            $allVendorIds = $pickupPoints->pluck('vendor_id')->unique()->toArray();
            
            // 批量查询供货商信息
            $vendors = [];
            if (!empty($allVendorIds)) {
                $vendors = Vendor::whereIn('id', $allVendorIds)
                    ->where('status', 1)
                    ->select('id', 'supplier_name', 'mobile')
                    ->get()
                    ->keyBy('id');
            }

            // 为每个门店组装供货商数据
            foreach ($storeIds as $storeId) {
                if (isset($pointsByStore[$storeId])) {
                    $vendorIds = $pointsByStore[$storeId]->pluck('vendor_id')->toArray();
                    $vendorList = [];
                    
                    foreach ($vendorIds as $vendorId) {
                        if (isset($vendors[$vendorId])) {
                            $vendor = $vendors[$vendorId];
                            $vendorList[] = [
                                'id' => $vendor->id,
                                'supplier_name' => $vendor->supplier_name,
                                'mobile' => $vendor->mobile,
                            ];
                        }
                    }
                    
                    $pickupVendorsMap[$storeId] = [
                        'supports_pickup' => !empty($vendorList),
                        'vendor_ids' => $vendorIds,
                        'vendors' => $vendorList
                    ];
                } else {
                    $pickupVendorsMap[$storeId] = [
                        'supports_pickup' => false,
                        'vendor_ids' => [],
                        'vendors' => []
                    ];
                }
            }
        } catch (\Exception $e) {
            $pickupVendorsMap = array_fill_keys($storeIds, [
                'supports_pickup' => false,
                'vendor_ids' => [],
                'vendors' => []
            ]);
        }

        return $pickupVendorsMap;
    }

    /**
     * 格式化距离显示
     */
    private function formatDistance($distance)
    {
        if ($distance < 1000) {
            return round($distance) . 'm';
        } else {
            return round($distance / 1000, 1) . 'km';
        }
    }

    /**
     * 构建完整的商家地址（包含市和区）
     *
     * @param object $store 商家对象
     * @return string 完整地址
     */
    private function buildFullAddress($store)
    {
        $address = $store->address ?? '';
        
        // 如果商家没有省市区信息，直接返回原地址
        if (empty($store->province_id) || empty($store->city_id) || empty($store->district_id)) {
            return $address;
        }
        
        try {
            // 获取省市区名称
            $province = Address::where('id', $store->province_id)->value('areaname');
            $city = Address::where('id', $store->city_id)->value('areaname');
            $district = Address::where('id', $store->district_id)->value('areaname');
            
            // 构建完整地址
            $fullAddress = '';
            if ($province) {
                $fullAddress .= $province;
            }
            if ($city && $city !== $province) {
                $fullAddress .= $city;
            }
            if ($district && $district !== $city) {
                $fullAddress .= $district;
            }
            
            // 如果原地址不包含省市信息，则拼接
            if (!empty($address) && !empty($fullAddress)) {
                // 检查原地址是否已经包含省市信息
                $hasProvince = $province && strpos($address, $province) !== false;
                $hasCity = $city && strpos($address, $city) !== false;
                $hasDistrict = $district && strpos($address, $district) !== false;
                
                if (!$hasProvince && !$hasCity && !$hasDistrict) {
                    // 原地址不包含省市信息，则拼接
                    $fullAddress .= $address;
                } else {
                    // 原地址已包含省市信息，直接返回原地址
                    $fullAddress = $address;
                }
            } elseif (empty($address)) {
                // 如果没有原地址，只返回省市信息
                return $fullAddress;
            } else {
                // 如果没有省市信息，返回原地址
                $fullAddress = $address;
            }
            
            return $fullAddress;
            
        } catch (\Exception $e) {
            // 出错时返回原地址
            return $address;
        }
    }

    /**
     * 解析商品接口的查询范围（同城/全国）
     *
     * @param \Illuminate\Http\Request $request
     * @return string
     */
    private function resolveProductScope(Request $request): string
    {
        $scope = strtolower((string) $this->getParam($request, 'scope', 'city'));
        return in_array($scope, ['national', 'city'], true) ? $scope : 'city';
    }

    /**
     * 查询banner
     */
    public function banners(Request $request)
    {
        $provinceId = $this->getParam($request, 'province_id');
        $cityId     = $this->getParam($request, 'city_id');
        $districtId = $this->getParam($request, 'district_id');

        if (empty($provinceId) || empty($cityId) || empty($districtId)) {
            return response()->json([
                'result' => 0,
                'msg'    => '省市区参数不能为空',
                'data'   => [],
            ]);
        }

        $cacheKey = "samecity:banners:{$provinceId}:{$cityId}:{$districtId}";
        $cached   = Cache::get($cacheKey);
        if ($cached) {
            $cached['from_cache'] = true;
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $cached
            ]);
        }

        try {
            // 查询数据
            $banners = AdImage::where('position_id', 1)
                ->whereNull('deleted_at')
                ->get();
            
            $banners = $banners->map(function ($item) {
                return [
                    'id'         => $item->id,
                    'title'      => $item->title ?? '',
                    'image_url'  => $item->full_image_url ?? '',
                    'url'        => $item->url ?? '',
                    'sort_order' => $item->sort_order ?? 0,
                ];
            })->toArray();

            $result = [
                'banners'    => $banners,
                'from_cache' => false,
            ];
            
            Cache::put($cacheKey, $result, 600);  // 10分钟
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $result
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 查询热销商品（优化版本）
     */
    public function hotProducts(Request $request)
    {
        $scope     = $this->resolveProductScope($request);
        $provinceId = $this->getParam($request, 'province_id');
        $cityId     = $this->getParam($request, 'city_id');
        $districtId = $this->getParam($request, 'district_id');

        $useLocation = $scope === 'city' && $provinceId && $cityId && $districtId;
        if ($scope === 'city' && ! $useLocation) {
            \Log::warning('[热销接口] 未提供完整定位参数，已回退至全国数据', [
                'province_id' => $provinceId,
                'city_id' => $cityId,
                'district_id' => $districtId,
            ]);
            $scope = 'national';
        }

        $cacheKey = $useLocation
            ? "samecity:hot_products:{$provinceId}:{$cityId}:{$districtId}"
            : "samecity:hot_products:national";
        $cached   = Cache::get($cacheKey);
        if ($cached) {
            $cached['from_cache'] = true;
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $cached
            ]);
        }

        try {
            // 使用 HhmGoods 模型查询 - 按销量取热卖商品（取前10条）
            $query = HhmGoods::query()
                ->join('ims_yz_store as s', 's.id', '=', 'ims_hhm_goods.store_id')
                ->where('s.is_hide', 0)
                ->where('s.operating_state', 0)
                ->where('ims_hhm_goods.status', 1)
                ->where('ims_hhm_goods.is_deleted', 0);

            if ($useLocation) {
                $query->where('s.province_id', $provinceId)
                    ->where('s.city_id', $cityId)
                    ->where('s.district_id', $districtId);
            }
            
            $hotProducts = $query->select(
                    'ims_hhm_goods.id', 
                    'ims_hhm_goods.title', 
                    'ims_hhm_goods.thumb', 
                    'ims_hhm_goods.price', 
                    'ims_hhm_goods.market_price', 
                    'ims_hhm_goods.real_sales',
                    'ims_hhm_goods.has_option',
                    'ims_hhm_goods.created_at',
                    's.id as store_id',
                    's.store_name',
                    's.thumb as store_thumb',
                    's.address as store_address',
                    's.mobile as store_mobile'
                )
                ->orderBy('ims_hhm_goods.real_sales', 'desc')  // 按销量排序
                ->limit(3)
                ->get();
            
            $hotProducts = $hotProducts->map(function ($item) {
                    try {
                        // 如果商品有规格，计算最低价格
                        $displayPrice = $item->price;
                        $displayMarketPrice = $item->market_price;
                        
                        if ($item->has_option) {
                            $options = HhmGoodsOption::where('goods_id', $item->id)
                                ->where('is_enabled', 1)
                                ->orderBy('product_price', 'asc')
                                ->get();
                            
                            if ($options->isNotEmpty()) {
                                $displayPrice = $options->min('product_price');
                                $displayMarketPrice = $options->min('market_price');
                            }
                        }
                        
                        // 处理图片 URL
                        $thumbUrl = ImageUrlService::processImageUrl($item->thumb);
                        $storeThumbUrl = ImageUrlService::processImageUrl($item->store_thumb);
                        
                        $result = [
                            'id'           => $item->id,
                            'title'        => $item->title,
                            'thumb'        => $thumbUrl,
                            'price'        => $displayPrice,
                            'market_price' => $displayMarketPrice,
                            'real_sales'   => $item->real_sales,
                            'created_at'   => $item->created_at,
                            'store'        => [
                                'id'      => $item->store_id,
                                'name'    => $item->store_name,
                                'thumb'   => $storeThumbUrl,
                                'address' => $item->store_address,
                                'mobile'  => $item->store_mobile,
                            ],
                        ];
                        
                        return $result;
                    } catch (\Exception $itemException) {
                        \Log::error('[热销接口] 商品处理失败', [
                            'goods_id' => $item->id ?? null,
                            'error' => $itemException->getMessage()
                        ]);
                        return null;
                    }
                })
                ->filter()
                ->values()
                ->toArray();

            $result = [
                'hot_products' => $hotProducts,
                'from_cache'   => false,
            ];
            
            Cache::put($cacheKey, $result, 600);  // 10分钟
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[热销接口] 接口异常', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 查询新品
     */
    public function newProducts(Request $request)
    {
        $scope      = $this->resolveProductScope($request);
        $provinceId = $this->getParam($request, 'province_id');
        $cityId     = $this->getParam($request, 'city_id');
        $districtId = $this->getParam($request, 'district_id');

        $useLocation = $scope === 'city' && $provinceId && $cityId && $districtId;
        if ($scope === 'city' && ! $useLocation) {
            \Log::warning('[新品接口] 未提供完整定位参数，已回退至全国数据', [
                'province_id' => $provinceId,
                'city_id' => $cityId,
                'district_id' => $districtId,
            ]);
            $scope = 'national';
        }

        $cacheKey = $useLocation
            ? "samecity:new_products:{$provinceId}:{$cityId}:{$districtId}"
            : "samecity:new_products:national";
        $cached   = Cache::get($cacheKey);
        if ($cached) {
            $cached['from_cache'] = true;
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $cached
            ]);
        }

        try {
            
            // 使用 HhmGoods 模型查询 - 按创建时间取最新的3条商品
            $query = HhmGoods::query()
                ->join('ims_yz_store as s', 's.id', '=', 'ims_hhm_goods.store_id')
                ->where('s.is_hide', 0)
                ->where('s.operating_state', 0)
                ->where('ims_hhm_goods.status', 1)
                ->where('ims_hhm_goods.is_deleted', 0);
                // 移除 is_new 条件，直接按创建时间排序取最新3条

            if ($useLocation) {
                $query->where('s.province_id', $provinceId)
                    ->where('s.city_id', $cityId)
                    ->where('s.district_id', $districtId);
            }
            
            $newProducts = $query->select(
                    'ims_hhm_goods.id', 
                    'ims_hhm_goods.title', 
                    'ims_hhm_goods.thumb', 
                    'ims_hhm_goods.price', 
                    'ims_hhm_goods.market_price', 
                    'ims_hhm_goods.real_sales',
                    'ims_hhm_goods.has_option',
                    'ims_hhm_goods.created_at',
                    's.id as store_id',
                    's.store_name',
                    's.thumb as store_thumb',
                    's.address as store_address',
                    's.mobile as store_mobile'
                )
                ->orderBy('ims_hhm_goods.created_at', 'desc')
                ->limit(3)
                ->get();
            
            $newProducts = $newProducts->map(function ($item) {
                    try {
                        // 如果商品有规格，计算最低价格
                        $displayPrice = $item->price;
                        $displayMarketPrice = $item->market_price;
                        
                        if ($item->has_option) {
                            $options = HhmGoodsOption::where('goods_id', $item->id)
                                ->where('is_enabled', 1)
                                ->orderBy('product_price', 'asc')
                                ->get();
                            
                            if ($options->isNotEmpty()) {
                                $displayPrice = $options->min('product_price');
                                $displayMarketPrice = $options->min('market_price');
                            }
                        }
                        
                        // 处理图片 URL
                        $thumbUrl = ImageUrlService::processImageUrl($item->thumb);
                        $storeThumbUrl = ImageUrlService::processImageUrl($item->store_thumb);
                        
                        $result = [
                            'id'           => $item->id,
                            'title'        => $item->title,
                            'thumb'        => $thumbUrl,
                            'price'        => $displayPrice,
                            'market_price' => $displayMarketPrice,
                            'real_sales'   => $item->real_sales,
                            'created_at'   => $item->created_at,
                            'store'        => [
                                'id'      => $item->store_id,
                                'name'    => $item->store_name,
                                'thumb'   => $storeThumbUrl,
                                'address' => $item->store_address,
                                'mobile'  => $item->store_mobile,
                            ],
                        ];
                        
                        return $result;
                    } catch (\Exception $itemException) {
                        \Log::error('[新品接口] 商品处理失败', [
                            'goods_id' => $item->id ?? null,
                            'error' => $itemException->getMessage()
                        ]);
                        return null;
                    }
                })
                ->filter()
                ->values()
                ->toArray();

            $result = [
                'new_products' => $newProducts,
                'from_cache'   => false,
            ];
            
            Cache::put($cacheKey, $result, 600);  // 10分钟
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            \Log::error('[新品接口] 接口异常', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 查询推荐商品 - 基于商品群组逻辑
     */
    public function recommendProducts(Request $request)
    {
        $scope      = $this->resolveProductScope($request);
        $provinceId = $this->getParam($request, 'province_id');
        $cityId     = $this->getParam($request, 'city_id');
        $districtId = $this->getParam($request, 'district_id');

        $debugInfo = [
            'scope' => $scope,
        ];

        $recommendProducts = $this->getRecommendProductsByGroups($provinceId, $cityId, $districtId, $debugInfo, $scope);

        // 如果没有找到商品，返回空结果（不展示整个菜单）
        if (empty($recommendProducts)) {
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => [
                    'recommend_products' => [],
                    'debug_info' => $debugInfo,
                    'from_cache' => false,
                ]
            ]);
        }

        return response()->json([
            'result' => 1,
            'msg'    => '获取成功',
            'data'   => [
                'recommend_products' => $recommendProducts,
                'debug_info' => $debugInfo,
                'from_cache' => false,
            ],
        ]);
    }

    /**
     * 通过商品群组查询推荐商品
     *
     * @param string $provinceId 省ID
     * @param string $cityId 市ID
     * @param string $districtId 区ID
     * @param array $debugInfo 调试信息引用
     * @param string $scope 查询范围（city / national）
     * @return array 推荐商品列表
     */
    private function getRecommendProductsByGroups($provinceId, $cityId, $districtId, &$debugInfo, $scope = 'city')
    {
        $scope = strtolower($scope);
        $isNational = $scope === 'national';
        $useLocation = ! $isNational && $provinceId && $cityId && $districtId;

        if (! $useLocation) {
            $isNational = true;
        }

        $cacheKey = $isNational
            ? "samecity:recommend_products:national"
            : "samecity:recommend_products:{$provinceId}:{$cityId}:{$districtId}";
        $cacheTtl = 600;  // 10分钟
        $cached   = Cache::get($cacheKey);
        if ($cached) {
            return $cached;
        }

        try {
            $query = HhmGoods::query()
                ->join('ims_yz_store as s', 's.id', '=', 'ims_hhm_goods.store_id')
                ->where('s.is_hide', 0)
                ->where('s.operating_state', 0)
                ->where('status', 1)
                ->where('is_deleted', 0)
                ->where('is_recommand', 1)
                ->select(
                    'ims_hhm_goods.id',
                    'ims_hhm_goods.title',
                    'ims_hhm_goods.thumb',
                    'ims_hhm_goods.price',
                    'ims_hhm_goods.market_price',
                    'ims_hhm_goods.created_at'
                );

            if ($useLocation) {
                $query->where('s.province_id', $provinceId)
                    ->where('s.city_id', $cityId)
                    ->where('s.district_id', $districtId);
            }

            $goodsRows = $query
                ->orderBy('ims_hhm_goods.created_at', 'desc')
                ->limit(3)
                ->get();

            if ($goodsRows->isEmpty()) {
                $debugInfo['no_products_found'] = true;
                Cache::put($cacheKey, [], $cacheTtl);
                return [];
            }

            $products = $goodsRows->map(function ($item) {
                return [
                    'id'           => $item->id,
                    'title'        => $item->title,
                    'thumb'        => $item->thumb,
                    'price'        => $item->price,
                    'market_price' => $item->market_price,
                    'created_at'   => $item->created_at,
                ];
            })->toArray();

            $debugInfo['final_products_count'] = count($products);
            $debugInfo['query_success'] = true;

            Cache::put($cacheKey, $products, $cacheTtl);

            return $products;

        } catch (\Exception $e) {
            $debugInfo['error'] = $e->getMessage();
            $debugInfo['query_failed'] = true;
            
            // 缓存空结果，避免重复查询
            Cache::put($cacheKey, [], $cacheTtl);
            
            return [];
        }
    }

    /**
     * 查询附近商家（分页）
     */
    public function nearbyStores(Request $request)
    {
        $page  = max(1, (int) $this->getParam($request, 'page', 1));
        $limit = max(1, (int) $this->getParam($request, 'limit', 10));
        $lat   = $this->getParam($request, 'lat');
        $lng   = $this->getParam($request, 'lng');
        
        // 设置默认经纬度（武汉江汉路）
        if (empty($lat)) $lat = 30.584;
        if (empty($lng)) $lng = 114.285;

        // 生成缓存键
        $cacheKey = "samecity:nearby_stores:" . md5($lat . '_' . $lng . '_' . $page . '_' . $limit);
        
        // 尝试从缓存获取
        $cached = Cache::get($cacheKey);
        if ($cached) {
            $cached['from_cache'] = true;
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $cached
            ]);
        }

        try {
            $userLat = (float) $lat;
            $userLng = (float) $lng;
            
            // 查询所有商家，不再限制距离范围
            $query = Store::query()
                ->where('is_hide', 0)
                ->where('operating_state', 0)
                ->selectRaw(
                    "id, store_name, thumb, address, mobile, longitude, latitude, created_at, category_id, dispatch_type, province_id, city_id, district_id,
                    (6371000 * 2 * ASIN(SQRT(
                        POW(SIN((? * PI() / 180 - latitude * PI() / 180) / 2), 2) +
                        COS(? * PI() / 180) * COS(latitude * PI() / 180) *
                        POW(SIN((? * PI() / 180 - longitude * PI() / 180) / 2), 2)
                    ))) AS distance",
                    [$userLat, $userLat, $userLng]
                )
                ->orderBy('distance', 'asc');
                
            $total = (clone $query)->count();
            $totalPages = ceil($total / $limit);
            $stores = $query->offset(($page - 1) * $limit)->limit($limit)->get();
            
            // 批量获取分类信息
            $categoryIds = $stores->pluck('category_id')->filter()->unique()->toArray();
            $categories = [];
            if (!empty($categoryIds)) {
                $categories = StoreCategory::query()
                    ->whereIn('id', $categoryIds)
                    ->pluck('name', 'id')
                    ->toArray();
            }
            
            // 批量获取置换类型信息
            $storeIds = $stores->pluck('id')->toArray();
            $swapTypesMap = $this->getBatchStoreSwapTypes($storeIds);
            
            // 批量获取供货商信息（用于判断上门自提）
            $pickupVendorsMap = $this->getBatchStorePickupVendors($storeIds);
            
            $result = $stores->map(function ($store) use ($categories, $swapTypesMap, $pickupVendorsMap) {
                // ========== 注释掉原 dispatch_type 相关逻辑 ==========
                // $dispatchType = is_string($store->dispatch_type) ? json_decode($store->dispatch_type, true) : $store->dispatch_type;
                // $dispatchText = $this->getDispatchText($dispatchType);
                // ====================================================
                
                $categoryName = isset($categories[$store->category_id]) ? $categories[$store->category_id] : '未分类';
                $swapTypes = $swapTypesMap[$store->id] ?? [];
                
                // 获取供货商信息（判断上门自提）
                $pickupInfo = $pickupVendorsMap[$store->id] ?? [
                    'supports_pickup' => false,
                    'vendor_ids' => [],
                    'vendors' => []
                ];
                
                return [
                    'id'             => $store->id,
                    'store_name'     => $store->store_name,
                    'thumb'          => ImageUrlService::processImageUrl($store->thumb),
                    'address'        => $this->buildFullAddress($store),
                    'mobile'         => $store->mobile,
                    'longitude'      => $store->longitude,
                    'latitude'       => $store->latitude,
                    'created_at'     => $store->created_at,
                    'category_id'    => $store->category_id,
                    'category_name'  => $categoryName,
                    'category_thumb' => '',
                    'distance'       => $store->distance,
                    'distance_text'  => $this->formatDistance($store->distance),
                    // ========== 注释掉原 dispatch_type 字段 ==========
                    // 'dispatch_type'  => $dispatchType,
                    // 'dispatch'       => $dispatchText,
                    // ================================================
                    'supports_pickup' => $pickupInfo['supports_pickup'],
                    'vendor_ids'      => $pickupInfo['vendor_ids'],
                    'vendors'         => $pickupInfo['vendors'],
                    'swap_types'      => $swapTypes,
                    'average_score'   => 5,
                ];
            })->toArray();
            
            $pagination = [
                'total'       => $total,
                'page'        => $page,
                'limit'       => $limit,
                'total_pages' => $totalPages,
            ];
            
            $data = [
                'stores'     => $result,
                'pagination' => $pagination,
                'from_cache' => false,
            ];
            
            // 缓存结果，10分钟
            Cache::put($cacheKey, $data, 600);
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $data,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '查询失败: ' . $e->getMessage(),
                'data'   => [
                    'stores'     => [],
                    'pagination' => [
                        'total'       => 0,
                        'page'        => $page,
                        'limit'       => $limit,
                        'total_pages' => 0,
                    ],
                ],
            ]);
        }
    }

    /**
     * 查询推荐商家（分页）- 芸众版本逻辑
     */
    public function recommendStores(Request $request)
    {
        $provinceId = $this->getParam($request, 'province_id');
        $cityId     = $this->getParam($request, 'city_id');
        $districtId = $this->getParam($request, 'district_id');
        $page       = max(1, (int) $this->getParam($request, 'page', 1));
        $limit      = max(1, (int) $this->getParam($request, 'limit', 10));

        if (empty($provinceId) || empty($cityId) || empty($districtId)) {
            return response()->json([
                'result' => 0,
                'msg'    => '省市区参数不能为空',
                'data'   => [],
            ]);
        }

        $debugInfo = [];
        // 调用芸众版本的推荐商家查询逻辑
        list($stores, $pagination) = $this->getRecommendStores($provinceId, $cityId, $districtId, [], $debugInfo, $page, $limit);
        
        return response()->json([
            'result' => 1,
            'msg'    => '获取成功',
            'data'   => [
                'stores'     => $stores,
                'pagination' => $pagination,
                'debug_info' => $debugInfo,
            ],
        ]);
    }

    /**
     * 查询推荐商家（芸众版本逻辑）
     *
     * @param string $provinceId 省ID
     * @param string $cityId 市ID
     * @param string $districtId 区ID
     * @param array $userLocation 用户经纬度（暂未使用）
     * @param array $debugInfo 调试信息引用
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array [商家列表, 分页信息]
     */
    private function getRecommendStores($provinceId, $cityId, $districtId, $userLocation, &$debugInfo, $page = 1, $limit = 10)
    {
        $cacheKey = "samecity:recommend:{$provinceId}:{$cityId}:{$districtId}:page{$page}:limit{$limit}";
        $cacheTtl = 600;  // 10分钟
        $cached   = Cache::get($cacheKey);
        if ($cached) {
            return $cached;
        }
        
        try {
            // 1. 直接按省市区筛选推荐门店
            $query = Store::query()
                ->where('province_id', $provinceId)
                ->where('city_id', $cityId)
                ->where('district_id', $districtId)
                ->where('is_hide', 0)
                ->where('operating_state', 0)
                ->where('is_recommend', 1)
                ->select('id', 'store_name', 'thumb', 'address', 'mobile', 'longitude', 'latitude', 'created_at', 'category_id', 'dispatch_type', 'province_id', 'city_id', 'district_id')
                ->orderBy('created_at', 'desc');
                
            $total       = (clone $query)->count();
            $totalPages  = ceil($total / $limit);
            $stores      = $query->offset(($page - 1) * $limit)->limit($limit)->get();
            
            $categoryIds = $stores->pluck('category_id')->filter()->unique()->toArray();
            $categories  = [];
            if (!empty($categoryIds)) {
                try {
                    $categories = StoreCategory::query()
                        ->whereIn('id', $categoryIds)
                        ->pluck('name', 'id')
                        ->toArray();
                } catch (\Exception $catError) {
                    $debugInfo['category_error'] = $catError->getMessage();
                }
            }
            
            // 批量获取供货商信息（用于判断上门自提）
            $storeIds = $stores->pluck('id')->toArray();
            $pickupVendorsMap = $this->getBatchStorePickupVendors($storeIds);
            
            $result = $stores->map(function ($store) use ($categories, $pickupVendorsMap) {
                // ========== 注释掉原 dispatch_type 相关逻辑 ==========
                // $dispatchType = is_string($store->dispatch_type) ? json_decode($store->dispatch_type, true) : $store->dispatch_type;
                // $dispatchText = $this->getDispatchText($dispatchType);
                // ====================================================
                
                $categoryName = isset($categories[$store->category_id]) ? $categories[$store->category_id] : '未分类';
                $swapTypes    = $this->getStoreSwapTypes($store->id);
                $averageScore = method_exists($store, 'getAverageScoreAttribute') ? $store->average_score : 5;
                
                // 获取供货商信息（判断上门自提）
                $pickupInfo = $pickupVendorsMap[$store->id] ?? [
                    'supports_pickup' => false,
                    'vendor_ids' => [],
                    'vendors' => []
                ];
                
                return [
                    'id'             => $store->id,
                    'store_name'     => $store->store_name,
                    'thumb'          => ImageUrlService::processImageUrl($store->thumb),
                    'address'        => $this->buildFullAddress($store),
                    'mobile'         => $store->mobile,
                    'longitude'      => $store->longitude,
                    'latitude'       => $store->latitude,
                    'created_at'     => $store->created_at,
                    'category_id'    => $store->category_id,
                    'category_name'  => $categoryName,
                    'category_thumb' => '',
                    // ========== 注释掉原 dispatch_type 字段 ==========
                    // 'dispatch_type'  => $dispatchType,
                    // 'dispatch'       => $dispatchText,
                    // ================================================
                    'supports_pickup' => $pickupInfo['supports_pickup'],
                    'vendor_ids'      => $pickupInfo['vendor_ids'],
                    'vendors'         => $pickupInfo['vendors'],
                    'swap_types'      => $swapTypes,
                    'average_score'   => $averageScore,
                ];
            })->toArray();
            
            $resultArr = [$result, [
                'total'       => $total,
                'page'        => $page,
                'limit'       => $limit,
                'total_pages' => $totalPages,
            ]];
            
            if (!empty($result)) {
                Cache::put($cacheKey, $resultArr, $cacheTtl);
            }
            
            return $resultArr;
        } catch (\Exception $e) {
            $debugInfo['recommend_stores_error'] = $e->getMessage();
            $resultArr = [[], [
                'total'       => 0,
                'page'        => $page,
                'limit'       => $limit,
                'total_pages' => 0,
            ]];
            return $resultArr;
        }
    }

    /**
     * 查询最新入驻商家（分页）
     */
    public function newStores(Request $request)
    {
        $page  = max(1, (int) $this->getParam($request, 'page', 1));
        $limit = max(1, (int) $this->getParam($request, 'limit', 10));

        // 生成缓存键
        $cacheKey = "samecity:new_stores:" . md5($page . '_' . $limit);
        
        // 尝试从缓存获取
        $cached = Cache::get($cacheKey);
        if ($cached) {
            $cached['from_cache'] = true;
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $cached
            ]);
        }

        try {
            $query = Store::query()
                ->where('is_hide', 0)
                ->where('operating_state', 0)
                ->select('id', 'store_name', 'thumb', 'address', 'mobile', 'longitude', 'latitude', 'created_at', 'category_id', 'dispatch_type', 'province_id', 'city_id', 'district_id')
                ->orderBy('created_at', 'desc');
                
            $total = (clone $query)->count();
            $totalPages = ceil($total / $limit);
            $stores = $query->offset(($page - 1) * $limit)->limit($limit)->get();
            
            // 批量获取分类信息
            $categoryIds = $stores->pluck('category_id')->filter()->unique()->toArray();
            $categories = [];
            if (!empty($categoryIds)) {
                $categories = StoreCategory::query()
                    ->whereIn('id', $categoryIds)
                    ->pluck('name', 'id')
                    ->toArray();
            }
            
            // 批量获取置换类型信息
            $storeIds = $stores->pluck('id')->toArray();
            $swapTypesMap = $this->getBatchStoreSwapTypes($storeIds);
            
            // 批量获取供货商信息（用于判断上门自提）
            $pickupVendorsMap = $this->getBatchStorePickupVendors($storeIds);
            
            $result = $stores->map(function ($store) use ($categories, $swapTypesMap, $pickupVendorsMap) {
                // ========== 注释掉原 dispatch_type 相关逻辑 ==========
                // $dispatchType = is_string($store->dispatch_type) ? json_decode($store->dispatch_type, true) : $store->dispatch_type;
                // $dispatchText = $this->getDispatchText($dispatchType);
                // ====================================================
                
                $categoryName = isset($categories[$store->category_id]) ? $categories[$store->category_id] : '未分类';
                $swapTypes = $swapTypesMap[$store->id] ?? [];
                
                // 获取供货商信息（判断上门自提）
                $pickupInfo = $pickupVendorsMap[$store->id] ?? [
                    'supports_pickup' => false,
                    'vendor_ids' => [],
                    'vendors' => []
                ];
                
                return [
                    'id'             => $store->id,
                    'store_name'     => $store->store_name,
                    'thumb'          => ImageUrlService::processImageUrl($store->thumb),
                    'address'        => $this->buildFullAddress($store),
                    'mobile'         => $store->mobile,
                    'longitude'      => $store->longitude,
                    'latitude'       => $store->latitude,
                    'created_at'     => $store->created_at,
                    'category_id'    => $store->category_id,
                    'category_name'  => $categoryName,
                    'category_thumb' => '',
                    // ========== 注释掉原 dispatch_type 字段 ==========
                    // 'dispatch_type'  => $dispatchType,
                    // 'dispatch'       => $dispatchText,
                    // ================================================
                    'supports_pickup' => $pickupInfo['supports_pickup'],
                    'vendor_ids'      => $pickupInfo['vendor_ids'],
                    'vendors'         => $pickupInfo['vendors'],
                    'swap_types'      => $swapTypes,
                    'average_score'   => 5,
                ];
            })->toArray();
            
            $pagination = [
                'total'       => $total,
                'page'        => $page,
                'limit'       => $limit,
                'total_pages' => $totalPages,
            ];
            
            $data = [
                'stores'     => $result,
                'pagination' => $pagination,
                'from_cache' => false,
            ];
            
            // 缓存结果，10分钟
            Cache::put($cacheKey, $data, 600);
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $data,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
}
